#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"

int main()
{
    int err;
    int s;
    char buff[256];
    struct sockaddr_in recv_addr;
    int recv_addr_len = sizeof(recv_addr);

    s = socket(AF_INET, SOCK_DGRAM, 0);
    if (s < 0)
    {
        perror("socket()");
        exit(1);
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(UDP_TEST_ADDR);
    addr.sin_port = htons(UDP_TEST_PORT);
    err = bind(s, (struct sockaddr *)&addr, sizeof(addr));
    if (err < 0)
    {
        perror("bind()");
        exit(1);
    }

    while (1)
    {
        memset(buff, 0, sizeof(buff));
        
        err = recvfrom(s, buff, sizeof(buff), 0, (struct sockaddr *)&recv_addr, &recv_addr_len);
        if (err < 0)
        {
            continue;
        }

        printf("%s\n", buff);

        char reply[256] = { '\0' };
        strcat(reply, "message [");
        strcat(reply, buff);
        strcat(reply, "] has been received!");
        err = sendto(s, reply, strlen(reply), 0, (struct sockaddr *)&recv_addr, recv_addr_len);
        if (err < 0)
        {
            perror("sendto()");
            continue;
        }
    }

    return 0;
}